#!/bin/bash

usage()
{
    echo 'Usage : Script -h <fledge_host> -mbh <mqtt_broker_host> -s <service_name> -psh <publish_subscrible_host> -o <output_type> -a <asset_name>'
}

### Check curl installation
if [! -x /usr/bin/curl ] ; then
    command -v curl >/dev/null 2>&1 || {echo >&2 "Please install wget"; exit 1}
fi


### Get input parameters
if ["$#" -ne 13]
then 
  usage
fi

while ["$1" != ""]; do
case $1 in
    -mbh )         shift
                   MQTT_BROKER_HOST=$1
                   ;;
        -s )       shift
                   SERVICE_NAME=$1
                   ;;
        -psh )     shift
                   PUB_SUB_HOST=$1
                   ;;
        -h )       shift
                   FLEDGE_HOST=$1
                   ;;
        -o )       shift
                   OUTPUT_TYPE=$1
                   ;;
        -a )       shift
                   ASSET_NAME=$1
                   ;;
    esac
    shift
done

if ["$MQTT_BROKER_HOST" = ""]
then
    usage
fi
if ["$SERVICE_NAME" = ""]
then
    usage
fi
if ["$PUB_SUB_HOST" = ""]
then
    usage
fi

FLEDGE_SVC_URL="/fledge/service"
FLEDGE_ASSERT_URL="/fledge/mqtt/$ASSER_NAME"

### Subscribe mqtt service to certain broker
curl -H "Content-Type: Application/json" -d {"name": "$SERVICE_NAME", "type": "south", "address": "$PUB_SUB_HOST", "plugin" :"mqtt-readings", "enabled":true, "config": {"brokerHost": {"value": "$MQTT_BROKER_HOST"}}} \
     -X Post $FLEDGE_HOST/$FLEDGE_SVC_URL

### 
if ["$OUTPUT_TYPE"="FILE"]
curl -H "Content-Type: Application/json" -X GET $FLEDGE_HOST/$FLEDGE_ASSERT_URL -o fledge_assert.json
fi